﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace MvcStudy.Models
{
    public class HtmlFilter : ActionFilterAttribute
    {
        #region = IsAvailable =

        private bool _isavailable = true;

        public bool IsAvailable
        {
            get { return _isavailable; }
            set { _isavailable = value; }
        }

        #endregion
        public HtmlFilter() { }
        public HtmlFilter(bool isAvailable)
        {
            _isavailable = isAvailable;
        }
        public string SetGray(string text)
        {
            text = HtmlHelper.Compress(text);
            if (DateTime.Now.Month == 4 && DateTime.Now.Day == 21)
            {
                text = Regex.Replace(text, "</head>", @"<style type=""text/css"">html {filter:gray;}</style></head>  
", RegexOptions.IgnoreCase);
            }
            return text;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
            if (!IsAvailable)
#if DEBUG
                return;
#endif
            filterContext.RequestContext.HttpContext.Response.Filter = new HtmlStreamFilter(filterContext.RequestContext.HttpContext.Response.Filter, filterContext.RequestContext.HttpContext.Response.ContentEncoding, SetGray);
        }
    }
}